package net.uiiang.android.alkaid;

import net.uiiang.android.alkaid.helper.FavoriteAdapter;
import net.uiiang.android.alkaid.helper.FileManagerDbAdapter;
import net.uiiang.android.alkaid.object.FavoriteObject;
import net.uiiang.android.alkaid.object.FileManagerDbObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class FavoriteList extends ListActivity {

    private FileManagerDbAdapter fileManagerDbAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.favorite_list);
        registerForContextMenu(getListView());
    }

    @Override
    protected void onResume() {
        super.onResume();
        fileManagerDbAdapter = new FileManagerDbAdapter(this);
        fileManagerDbAdapter.open();
        this.fillData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        super.onCreateOptionsMenu(menu);
        // 关于菜单
        menu.add(0, Constant.OPTION_MENU_ITEM_ABOUT, 99, R.string.menu_about);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case Constant.OPTION_MENU_ITEM_ABOUT: {
            Intent i = new Intent(this, About.class);
            startActivity(i);
            return true;
        }
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, Constant.FAVORITE_MENU_ITEM_RENAME, 0,
                R.string.reInputAliasName);
        menu
                .add(0, Constant.FAVORITE_MENU_ITEM_DELETE, 1,
                        R.string.menu_delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info;
        try {
            info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            return false;
        }
        final long id = info.id;
        switch (item.getItemId()) {
        case Constant.FAVORITE_MENU_ITEM_RENAME: {
            // mDbHelper.deleteNote(info.id);
            final FavoriteObject favoriteObject = this
                    .getFavoriteObjectById(info.id);
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.new_directory,
                    null);
            TextView tv = ((TextView) textEntryView
                    .findViewById(R.id.new_directory_name_view));
            tv.setText(R.string.inputAliasName);
            EditText editText = ((EditText) textEntryView
                    .findViewById(R.id.new_directory_name_edit));
            editText.setText(favoriteObject.getAlias());
            new AlertDialog.Builder(this).setIcon(
                    android.R.drawable.ic_menu_add).setTitle(
                    R.string.menu_add_favorite).setView(textEntryView)
                    .setPositiveButton(R.string.btn_confirm,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    // String aliasName =
                                    // editText.getText().toString();
                                    String newDirectoryName = (String) ((EditText) textEntryView
                                            .findViewById(R.id.new_directory_name_edit))
                                            .getText().toString();
                                    fileManagerDbAdapter.updateFavorite(id,
                                            newDirectoryName);
                                    fillData();
                                }
                            }).setNegativeButton(R.string.btn_cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    return;
                                }
                            }).show();
            return true;
        }
        case Constant.FAVORITE_MENU_ITEM_DELETE: {
            fileManagerDbAdapter.deleteFavorite(info.id);
            fillData();
            return true;
        }
        }
        return super.onContextItemSelected(item);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        FavoriteObject favoriteObject = this.getFavoriteObjectById(id);
        if (favoriteObject.getFilePath().startsWith(
                Environment.getExternalStorageDirectory().getAbsolutePath())) {

            Intent intent = BrowseFileTab.getBrowseDefualtSdCardIntent();
            intent.putExtra(Constant.OPEN_PATH_STR, favoriteObject
                    .getFilePath());
            BrowseFileTab.tabSdCard.setContent(intent);
            BrowseFileTab.tabHost.setCurrentTab(Constant.TAB_SD_CARD_INDEX);
            // BrowseFileTab.tab1.setContent(intent);
        } else {
            Intent intent = BrowseFileTab.getBrowseDefaultRootIntent();
            intent.putExtra(Constant.OPEN_PATH_STR, favoriteObject
                    .getFilePath());
            BrowseFileTab.tabRoot.setContent(intent);
            BrowseFileTab.tabHost.setCurrentTab(Constant.TAB_ROOT_INDEX);
            // BrowseFileTab.tab2.setContent(intent);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        fileManagerDbAdapter.close();
    }

    private FavoriteObject getFavoriteObjectById(long id) {
        Cursor favoriteCursor = fileManagerDbAdapter.fetchFavorite(id);
        startManagingCursor(favoriteCursor);
        int filePathIndex = favoriteCursor
                .getColumnIndexOrThrow(FileManagerDbObject.Favorite.FILE_PATH);
        int fileTypeIndex = favoriteCursor
                .getColumnIndexOrThrow(FileManagerDbObject.Favorite.FILE_TYPE);
        int fileNameIndex = favoriteCursor
                .getColumnIndexOrThrow(FileManagerDbObject.Favorite.FILE_NAME);
        int aliasIndex = favoriteCursor
                .getColumnIndexOrThrow(FileManagerDbObject.Favorite.ALIAS);

        FavoriteObject favoriteObject = new FavoriteObject();
        favoriteObject.setAlias(favoriteCursor.getString(aliasIndex));
        favoriteObject.setFileName(favoriteCursor.getString(fileNameIndex));
        favoriteObject.setFilePath(favoriteCursor.getString(filePathIndex));
        favoriteObject.setFileType(favoriteCursor.getString(fileTypeIndex));
        // if(favoriteCursor!=null){
        // favoriteCursor.close();
        // favoriteCursor = null;
        // }
        return favoriteObject;
    }

    private void fillData() {
        Cursor favoriteCursor = fileManagerDbAdapter.fetchAllFavorite();
        startManagingCursor(favoriteCursor);

        String[] from = new String[] { FileManagerDbObject.Favorite.ALIAS,
                FileManagerDbObject.Favorite.FILE_PATH };

        int[] to = new int[] { R.id.title, R.id.desc };

        FavoriteAdapter favorite = new FavoriteAdapter(this,
                R.layout.list_item_icon_text, favoriteCursor, from, to);
        setListAdapter(favorite);
        // if(favoriteCursor!=null){
        // favoriteCursor.close();
        // favoriteCursor = null;
        // }
    }
}
